package com.bear.atlassianmcp.oauth.config;

import com.bear.atlassianmcp.oauth.strategy.AuthenticationStrategyFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;

/**
 * OAuth 配置类
 * 负责配置 OAuth 相关的 Bean 和参数
 */
@Configuration
public class OAuthConfig {
    
    /**
     * 配置 OAuth 专用的 RestTemplate
     */
    @Bean("oauthRestTemplate")
    public RestTemplate oauthRestTemplate() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout((int) Duration.ofSeconds(30).toMillis());
        factory.setReadTimeout((int) Duration.ofSeconds(60).toMillis());
        
        return new RestTemplate(factory);
    }
    
    /**
     * 配置 ObjectMapper 用于 OAuth Token 序列化
     */
    @Bean("oauthObjectMapper")
    public ObjectMapper oauthObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.findAndRegisterModules(); // 注册 JavaTime 模块等
        return mapper;
    }
    
    /**
     * 在应用启动时验证认证配置
     */
    @Bean
    public AuthConfigValidator authConfigValidator(AuthenticationStrategyFactory strategyFactory) {
        return new AuthConfigValidator(strategyFactory);
    }
    
    /**
     * 认证配置验证器
     */
    public static class AuthConfigValidator {
        private final AuthenticationStrategyFactory strategyFactory;
        
        public AuthConfigValidator(AuthenticationStrategyFactory strategyFactory) {
            this.strategyFactory = strategyFactory;
            // 在构造时进行验证
            validateConfigurations();
        }
        
        private void validateConfigurations() {
            try {
                strategyFactory.validateAllConfigurations();
            } catch (Exception e) {
                // 不抛出异常，只记录警告，允许应用启动
                System.err.println("Warning: Authentication configuration validation failed: " + e.getMessage());
            }
        }
    }
}
